package com.zj.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seventh.common.pojo.Payload;
import com.seventh.common.pojo.R;
import com.seventh.common.utils.JwtUtils;

import com.zj.system.config.RsaKeyProperties;
import com.zj.system.mapper.MenuMapper;
import com.zj.system.pojo.entity.SysMenu;
import com.zj.system.pojo.entity.User;
import com.zj.system.service.MenuSer;
import com.zj.system.utils.WebUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: clms-seventh
 * @description: menu的逻辑控制层
 * @author: 张静
 * @create: 2021-07-18 20:10
 **/
@Service
public class MenuSerImpl implements MenuSer {
    @Resource
    private MenuMapper menuMapper;

    @Autowired
    private RsaKeyProperties rsaKeyProperties;
    @Override
    public R selectFunction() {
        HttpServletRequest request= WebUtil.getRequest();
        String token = request.getHeader("token");
        Payload<User> info = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
        Integer userId = info.getUserInfo().getUserId();
        List<SysMenu> father= menuMapper.selectFuntion(userId);
        List<SysMenu> firstMenu=new ArrayList<>();
        for(SysMenu menu:father){
            Integer a=0;
            if (a.equals(menu.getParentId())){
                firstMenu.add(menu);
            }
        }

        for (SysMenu first:firstMenu){
            first.setSonList(findSon(father,first.getMenuId()));
        }
//        System.out.println("我们穿的实体是"+firstMenu);

        return R.ok().put("father",firstMenu);
    }

    @Override
    public R fenFunction(Integer roleId) {

        List<SysMenu> father= menuMapper.selectMenuByRole(roleId);
        List<Integer> roleMenuIds=father.stream().map(item->{return item.getMenuId();}).collect(Collectors.toList());
        List<SysMenu> allList=menuMapper.selectList(null);
        List<SysMenu> firstMenu=new ArrayList<>();
        for(SysMenu menu:allList){
            Integer a=0;
            if (a.equals(menu.getParentId())){
                firstMenu.add(menu);
            }
        }
        for (SysMenu first:firstMenu){
            first.setSonList(findSon(allList,first.getMenuId()));
        }

        return R.ok().put("menus",firstMenu).put("roleMenuIds",roleMenuIds);
    }

    @Override
    @Transactional
    public R upMenu(Integer roleId, List<Integer> roleMenu) {
        menuMapper.deleteByRoleId(roleId);
        menuMapper.insertByRoleId(roleId, roleMenu);
        return R.ok();
    }
/*
    @Override
    public R sel(Integer pageSize, Integer currentPage, MenuVo vo) {
        Page<SysMenu> page=new Page<>(currentPage,pageSize);
        QueryWrapper<SysMenu> wrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(vo.getMenuName())){
            wrapper.like("menu_name",vo.getMenuName());
        }
        if(StringUtils.isNotEmpty(vo.getStartDate())){
            wrapper.ge("create_time",vo.getStartDate());
        }
        if(StringUtils.isNotEmpty(vo.getEndDate())){
            wrapper.le("create_time",vo.getEndDate());
        }
        menuMapper.selectPage(page,wrapper);
        return R.ok().put("tableData",page);
    }*/

    @Override
    public R upStatus(Integer menuId, Integer visible) {
        UpdateWrapper<SysMenu> wrapper=new UpdateWrapper();
        wrapper.eq("menu_id",menuId);
        wrapper.set("visible",visible);
        menuMapper.update(null,wrapper);
        return R.ok();
    }

    @Override
    public R ins(SysMenu menu) {
        User useUser = this.getToken();
        menu.setCreateBy(useUser.getUserName());
        menu.setCreateTime(LocalDateTime.now());
        menuMapper.insert(menu);
        return R.ok().put("message","添加成功");
    }

    @Override
    public R up(SysMenu menu) {
        User useUser = this.getToken();
        UpdateWrapper<SysMenu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("menu_name",menu.getMenuName());
        updateWrapper.eq("menu_id",menu.getMenuId());
        updateWrapper.set("parent_id",menu.getParentId());
        updateWrapper.set("url",menu.getUrl());
        updateWrapper.set("remark",menu.getRemark());
        updateWrapper.set("icon",menu.getIcon());
        updateWrapper.set("update_by",useUser.getUserName());
        updateWrapper.set("update_time",LocalDateTime.now());
        menuMapper.update(null,updateWrapper);
        return R.ok().put("message","修改成功");
    }

    @Override
    public R del(Integer menuId) {
        QueryWrapper<SysMenu> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id",menuId);
        List<SysMenu> menus = menuMapper.selectList(wrapper);
        if (menus.size()>0){
            return R.error().put("message","删除失败，旗下有子菜单不允许删除");
        }else {
            menuMapper.deleteById(menuId);
            return R.ok().put("message","删除成功");
        }

    }

    @Override
    public R selMenuName(SysMenu menu) {
        List<SysMenu> list=menuMapper.selectList(null);
        int result=0;
        for (SysMenu u:list) {
            if (menu.getMenuId()!=null){
                if (!u.getMenuId().equals(menu.getMenuId())){
                    if (u.getMenuName().equals(menu.getMenuName())){
                        result=1;
                        break;
                    }
                }
            }else {
                if (u.getMenuName().equals(menu.getMenuName())){
                    result=1;
                    break;
                }
            }
        }
        return R.ok().put("code",result);
    }

    @Override
    public R selById(Integer menuId) {
        SysMenu menu = menuMapper.selectById(menuId);
        return R.ok().put("menuInfo",menu);
    }

    @Override
    public R selParentId(SysMenu menu) {
        List<SysMenu> list=menuMapper.selectList(null);

        Iterator<SysMenu> iterator=list.iterator();
        while (iterator.hasNext())
        {
            SysMenu sysMenu = iterator.next();
            if(menu.getMenuId()!=null){

                if (sysMenu.getMenuId().equals(menu.getMenuId())){
                    iterator.remove();
                }else if (sysMenu.getParentId().equals(menu.getMenuId())){
                    iterator.remove();
                }
            }

        }
        System.out.println(list.size());
        System.out.println(iterator);
        SysMenu sysMenu=new SysMenu();
        sysMenu.setMenuName("一级菜单");
        sysMenu.setMenuId(0);
        list.add(sysMenu);

        return R.ok().put("fatherMenuList",list);
    }

    @Override
    public R getMenuTable() {
     List<SysMenu> allList=menuMapper.selectList(null);
        List<SysMenu> firstMenu=new ArrayList<>();
        for(SysMenu menu:allList){
            Integer a=0;
            if (a.equals(menu.getParentId())){
                firstMenu.add(menu);
            }
        }
        for (SysMenu first:firstMenu){
            first.setSonList(findSon(allList,first.getMenuId()));
        }

        return R.ok().put("menus",firstMenu);
    }


    private List<SysMenu> findSon(List<SysMenu> menus,Integer pid){

        List<SysMenu> children=new ArrayList<>();
        for(SysMenu child:menus){
            if (child.getParentId().equals(pid)){
                children.add(child);
            }
        }
        for (SysMenu c:children){

            c.setSonList(findSon(menus,c.getMenuId()));
        }
        return children;
    }
    private User getToken(){
        HttpServletRequest request= WebUtil.getRequest();
        String token = request.getHeader("token");
        Payload<User> info = JwtUtils.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), User.class);
        return info.getUserInfo();
    }
}
